package com.ryan.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.log4j.Logger;

public class DateUtil{
	  
    private static Logger log = Logger.getLogger(DateUtil.class);
    private static String timePattern = "HH:mm";

    private static String pattern ="yyyy-MM-dd";
    
	private static SimpleDateFormat format = new SimpleDateFormat(pattern);

	public DateUtil() {
	}
	
	
	public Object convert(Class<?> type, Object value) {
		if (value == null || "".equals(value.toString())) {
			return (String) null;
		} else {
			return value.toString();
		}
	}
	

    
    public static String getDateTimePattern() {
        return pattern + " HH:mm:ss.S";
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static final String getDate(Date aDate) {
        String returnValue = "";

        if (aDate != null) {
            returnValue = format.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @see java.text.SimpleDateFormat
     * @throws ParseException
     */
    public static final Date convertStringToDate(String aMask, String strDate)
      throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '"
                      + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(timePattern, theTime);
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     * 
     * @return the current date
     * @throws ParseException
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = format.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * 
     * @see java.text.SimpleDateFormat
     */
    public static final String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.error("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     * 
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static final String convertDateToString(Date aDate) {
        return getDateTime(pattern, aDate);
    }

    /**
     * This method converts a String to a date using the datePattern
     * 
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * 
     * @throws ParseException
     */
    public static Date convertStringToDate(String strDate)
      throws ParseException {
        Date aDate = null;

        try {
            if (log.isDebugEnabled()) {
                log.debug("converting date with pattern: " + pattern);
            }

            aDate = convertStringToDate(pattern, strDate);
        } catch (ParseException pe) {
            log.error("Could not convert '" + strDate
                      + "' to a date, throwing exception");
            pe.printStackTrace();
            throw new ParseException(pe.getMessage(),
                                     pe.getErrorOffset());
                    
        }

        return aDate;
    }

	public static String date2StringYMD(Date date) {
		if (date != null)
			return new SimpleDateFormat("yyyy-MM-dd").format(date);
		else
			return "";
	}

	public static Date string2DateYMD(String date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date d_date = null;
		try {
			if (date != null) {
				d_date = format.parse(date);
			} else
				d_date = format.parse("1900-00-00");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d_date;
	}

	public static long string2LongYMD(String time) {
		long mm_ss = 0;
		if (time != null && !time.equals("")) {
			int firstPos = time.indexOf("-");
			int lastPos = time.lastIndexOf("-");
			int hh = Integer.parseInt(time.substring(0, firstPos));
			int mm = Integer.parseInt(time.substring(firstPos + 1, lastPos));
			int ss = Integer.parseInt(time
					.substring(lastPos + 1, time.length()));
			mm_ss = hh * 60 * 60 + mm * 60 + ss;
		}
		return mm_ss;
	}

	public static long string2LongHMS(String time) {
		long mm_ss = 0;
		if (time != null && !time.equals("")) {
			int firstPos = time.indexOf(":");
			int lastPos = time.lastIndexOf(":");
			int hh = Integer.parseInt(time.substring(0, firstPos));
			int mm = Integer.parseInt(time.substring(firstPos + 1, lastPos));
			int ss = Integer.parseInt(time
					.substring(lastPos + 1, time.length()));
			mm_ss = hh * 60 * 60 + mm * 60 + ss;
		}
		return mm_ss;
	}

	/**
	 * 获取现在时间
	 * 
	 * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	 */
	public static Date string2Date(String time,String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		Date currentTime = new Date();
		try {
			currentTime = formatter.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return currentTime;
	}
	
	/**
	 * 获取现在时间
	 * 
	 * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	 */
	public static Date date2String(String time , String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		Date currentTime = new Date();
		try {
			currentTime = formatter.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return currentTime;
	}
	public static String long2String(long time){
		Date date = new Date(time);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeStr = simpleDateFormat.format(date);
		return timeStr;
	}	
	
	public static String int2String(int time){
		Date date = new Date(time);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeStr = simpleDateFormat.format(date);
		return timeStr;
	}


	/**
	 * 得到当前时间
	 * @return 当前时间
	 */
	public static Date getCurrentDate(){
		return new Date(System.currentTimeMillis());
	}
	
	/**
	 * 时间加减
	 * @param date 时间
	 * @param dayCount 增加或者减少的天数 ，正数为增加，负数为减少
	 * @return 计算后的时间
	 */
	public static Date dateAdd(Date date,int dayCount){
		Calendar calendar = Calendar.getInstance(); 
		calendar.add(Calendar.DATE, +dayCount); 
		return calendar.getTime();
	}

	/**
	 * 按照传入的格式吧Date类型转化成String类型
	 * @param date
	 * @param format
	 * @return
	 */
	public static String date2String(Date date,String format){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.format(date);
	}
	
}
